package net.pws.oos.web.dto;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.pws.common.beanutils.BeanUtils;
import net.pws.common.persistence.EntityManager;
import net.pws.common.util.StringUtils;
import net.pws.oos.biz.model.Area;

public class AreaDto extends Area {
    
    /**
	 * 
	 */
    private static final long serialVersionUID = 7052938462269189255L;
    
    private String parentId;
    
    private String parentName;
    
    public String getParentId() {
        return parentId;
    }
    
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }
    
    public String getParentName() {
        return parentName;
    }
    
    public void setParentName(String parentName) {
        this.parentName = parentName;
    }
    
    @SuppressWarnings("rawtypes")
    public static AreaDto from(Map map) {
        AreaDto dto = new AreaDto();
        BeanUtils.copyProperties(dto, map);
        return dto;
    }
    
    public static AreaDto from(Area model) {
        return from(model, false);
    }
    
    public static AreaDto from(Area model, boolean copyParent) {
        AreaDto dto = new AreaDto();
        BeanUtils.copyProperties(dto, model, new String[] { "parent" });
        if (copyParent && model.getParent() != null) {
            Area parent = model.getParent();
            dto.setParentId(parent.getId());
            dto.setParentName(parent.getName());
        }
        return dto;
    }
    
    public static List<AreaDto> from(List<Area> models) {
        List<AreaDto> dtos = new ArrayList<AreaDto>();
        for (Area model : models) {
            dtos.add(from(model));
        }
        return dtos;
    }
    
    public static Area to(AreaDto dto, EntityManager entityManager) {
        Area model = null;
        if (StringUtils.isBlank(dto.getId())) {
            model = new Area();
        }
        else {
            model = entityManager.find(Area.class, dto.getId());
        }
        BeanUtils.copyProperties(model, dto, new String[] { "id",
                                                           "parent",
                                                           "deleted" });
        if (StringUtils.isNotBlank(dto.getParentId())) {
            model.setParent(entityManager.find(Area.class, dto.getParentId()));
        }
        return model;
    }
}
